//
//  ListViewController.m
//  盘盈贷1.2
//
//  Created by iOS on 15/3/6.
//  Copyright (c) 2015年 iOS. All rights reserved.
//

#import "ListViewController.h"
#import "ListTableViewCell.h"
#import "NetworkHandler.h"
#import "List.h"
#import "AFHTTPRequestOperationManager.h"
#import "ZaiquanTableViewCell.h"
#import "DetailViewController.h"
#import "Detail_fanggeViewController.h"
#import "Zaiquan.h"
#import "HMSegmentedControl.h"
#import "MJRefresh.h"

static const CGFloat MJDuration = 2.0;

@interface ListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UISegmentedControl *segment;
@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)NSMutableArray *array1;
@property (nonatomic, retain) NSString *apiString;
@property (nonatomic, retain)NSString *apiString1;
@property (nonatomic, retain)NSString *api;
@property (nonatomic, retain)NSMutableArray *arr;

@end

@implementation ListViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.title = @"产品列表";
        self.array = [NSMutableArray array];
        
        self.array1 = [NSMutableArray array];
        self.arr = [NSMutableArray array];
        self.api = @"http://www.cloudpeng.com";
        UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
        //back.image = [UIImage imageNamed:@"iconfont-liebiao.png"];
        back.title = @"返回";
        self.navigationItem.backBarButtonItem = back;
        self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    CGFloat width = self.view.frame.size.width;
//    CGFloat height = self.view.frame.size.height;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-4fangge.png"] style:UIBarButtonItemStyleDone target:self action:@selector(Clicked:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStyleDone target:self action:@selector(refresh:)];
   [self LoadingData];
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"P2P", @"供应链融资", @"众筹拍房"]];
    [segmentedControl setFrame:CGRectMake(5, 64, self.view.frame.size.width, 40)];
    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
   // [segmentedControl setSegmentEdgeInset:UIEdgeInsetsMake(10, 50, 0, 6)];
    [segmentedControl setSelectionIndicatorHeight:4.0f];
    
    [segmentedControl setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];
    [segmentedControl setContentVerticalAlignment:UIControlContentVerticalAlignmentFill];
    segmentedControl.selectionIndicatorColor = [UIColor orangeColor];
    [segmentedControl setTintColor:[UIColor orangeColor]];
    segmentedControl.tintColor = [UIColor orangeColor];
    [segmentedControl setTag:1];
    [self.view addSubview:segmentedControl];
    [segmentedControl release];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 103, self.view.frame.size.width, self.view.frame.size.height - 150) style:UITableViewStylePlain];
    //self.tableView.backgroundColor = [UIColor yellowColor];
    self.tableView.rowHeight = 95;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
}
- (void)segmentAction:(HMSegmentedControl *)segmentedControl

{
    
    switch (segmentedControl.selectedIndex) {
        case 0:
            self.apiString = [self.api stringByAppendingFormat:@":8102/product/lendlist?productcateid=1"];
            self.array = [NSMutableArray array];
            [self LoadingData];
            break;
        case 1:
            self.apiString = [self.api stringByAppendingFormat:@":8102/product/lendlist?productcateid=3"];
            self.array = [NSMutableArray array];
            [self LoadingData];
            break;
        case 2:
            self.apiString = [self.api stringByAppendingFormat:@":8102/product/lendlist?productcateid=2"];
            self.array = [NSMutableArray array];
            [self LoadingData];
            break;
        case 3:
            self.apiString = [self.api stringByAppendingFormat:@":8102/product/transferlist"];
            
            [self LoadingData];
            break;
    }
}
- (void)LoadingData
{
    if (self.apiString == nil) {
        self.apiString = [self.api stringByAppendingFormat:@":8102/product/lendlist?productcateid=1"];
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:self.apiString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            for (NSDictionary *dic in responseObject) {
                List *model = [[List alloc] initWithDictionary:dic];
              
              // self.userID = model.userid;
                
                [self.arr addObject:model];
            
            }
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"___________%@",error);
        }];
        
       [self.tableView reloadData];
       
    }
        if (self.segment.selectedSegmentIndex == 0 || self.segment.selectedSegmentIndex == 1 || self.segment.selectedSegmentIndex == 2) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:self.apiString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            for (NSDictionary *dic in responseObject) {
                List *model = [[List alloc] initWithDictionary:dic];
                [self.array addObject:model];
            }
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"~~~~~~~%@",error);
        }];

    }else {
        self.apiString1 = [self.api stringByAppendingFormat:@":8102/product/transferlist"];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:self.apiString1 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            for (NSDictionary *dic1 in responseObject) {
                Zaiquan *model1 = [[Zaiquan alloc] initWithDictionary:dic1];
                [self.array1 addObject:model1];
                
            }
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"~~~~~~~%@",error);
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.segment.selectedSegmentIndex == 0 || self.segment.selectedSegmentIndex == 1 || self.segment.selectedSegmentIndex == 2) {
        return [self.array count];
    } else {
        return [self.array1 count];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.segment.selectedSegmentIndex == 0|| self.segment.selectedSegmentIndex == 1||self.segment.selectedSegmentIndex == 2) {
        ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil) {
           cell = [[ListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
//        else{
//            //cell中本来就有一个subview，如果是重用cell，则把cell中自己添加的subview清除掉，避免出现重叠问题
//            //         [[cell.subviews objectAtIndex:1] removeFromSuperview];
//            for (UIView *subView in cell.contentView.subviews)
//            {
//                [subView removeFromSuperview];
//            }
//           [tableView reloadData];
//        }
        
        cell.nameTitle.text = [[self.array objectAtIndex:indexPath.row] Title];
        //下划线
//      NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:[[self.array objectAtIndex:indexPath.row] Title]];
//        
//        NSRange contentRange = {0, [content length]};
//        [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
//        
//        cell.nameTitle.attributedText = content;
        NSString *bid = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] BidRate]];
        if ([bid rangeOfString:@"."].length>0) {
            
            cell.yuqinianhua1.text = [NSString stringWithFormat:@"%@0%%", bid];
        }else{
            cell.yuqinianhua1.text = [NSString stringWithFormat:@"%@ .00%%", bid];
        }
       
        cell.nameTitle.textAlignment = NSTextAlignmentLeft;
        cell.yuqinianhua1.textAlignment = NSTextAlignmentLeft;
        cell.yuqinianhua.textAlignment = NSTextAlignmentLeft;
        cell.nameTitle.textAlignment = NSTextAlignmentLeft;
        cell.qi.text = [NSString stringWithFormat:@"%@个月起", [[self.array objectAtIndex:indexPath.row] Limit]];
        cell.gou1.text = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] LoanRate]];
        cell.bigModel.BidAmount = [[self.array objectAtIndex:indexPath.row] BidAmount];
        List *model1 = [self.array objectAtIndex:indexPath.row];
        cell.bigModel = model1;
        cell.bigModel = [self.array objectAtIndex:indexPath.row];
        cell.bigModel.Amount =[[self.array objectAtIndex:indexPath.row] Amount];
        int jin = [[NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] LoanRate]] intValue];
        if (jin > 10000) {
            int p = jin / 10000;
            cell.gou1.text = [NSString stringWithFormat:@"%d万", p];
            
        }else{
            cell.gou1.text = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] LoanRate]];
        }
        
        cell.gou1.textAlignment = NSTextAlignmentRight;
        
        
        NSString *fang = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] IsHouseLoan]];
        NSString *car = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] IsCarLoan]];
        NSString *dan = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] IsGuaranteeLoan]];
        if ([dan isEqual:@"1"]) {
            [cell.tubiao setImage:[UIImage imageNamed:@"list_dan.png"]];
        }
        if ([fang isEqual:@"1"]) {
            [cell.tubiao setImage:[UIImage imageNamed:@"list_fang.png"]];
        }
        if ([car isEqual:@"1"]) {
            [cell.tubiao setImage:[UIImage imageNamed:@"list_che.png"]];
        }
        if ([car isEqual:@"0"] && [dan isEqual:@"0"] && [fang isEqual:@"0"]) {
            [cell.tubiao setImage:[UIImage imageNamed:@""]];
        }
        return cell;
    }
    
    
    else {
        ZaiquanTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell1 == nil) {
            cell1 = [[ZaiquanTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"reuse"];
            
        }
        cell1.nameTitle.text = [[self.array1 objectAtIndex:indexPath.row] Title];
        cell1.name1.text = [[self.array1 objectAtIndex:indexPath.row] LoanRealName];
        cell1.zhuanrangjine1.text = [NSString stringWithFormat:@"%@",[[self.array1 objectAtIndex:indexPath.row] Amount]];
        cell1.yuanbiaoqixian1.text = [NSString stringWithFormat:@"%@个月",[[self.array1 objectAtIndex:indexPath.row] Limit]];
        cell1.nianhualiyi1.text = [NSString stringWithFormat:@"%@",[[self.array1 objectAtIndex:indexPath.row] Rate]];
        cell1.shengyujine1.text = [NSString stringWithFormat:@"%@",[[self.array1 objectAtIndex:indexPath.row] Amount]];
        cell1.shengyiqixian1.text = [NSString stringWithFormat:@"%@天",[[self.array1 objectAtIndex:indexPath.row] LastDays]];
        
        cell1.zaiquan.BidAmount = [[self.array objectAtIndex:indexPath.row] BidAmount];
        Zaiquan *model2 = [self.array objectAtIndex:indexPath.row];
        cell1.zaiquan = model2;
        NSInteger a = [[[self.array objectAtIndex:indexPath.row] Amount] floatValue];
        NSInteger b = [[[self.array objectAtIndex:indexPath.row] BidAmount] floatValue];
        CGFloat result = a / b;
        
        cell1.rate.text = [NSString stringWithFormat:@"%.00f %%", result];
        return cell1;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    DetailViewController *detail = [[DetailViewController alloc] init];
    self.userID = [NSString stringWithFormat:@"%@", [[self.array objectAtIndex:indexPath.row] userid]];
    detail.userId = self.userID;
   
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
    
}
- (void)refresh:(UIBarButtonItem *)button
{
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(network:)];
    
    // 隐藏时间
    self.tableView.header.updatedTimeHidden = YES;
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
    
    // 此时self.tableView.header == self.tableView.legendHeader
    
}

- (void)network:(id)sender{
    [self.tableView reloadData];
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.header endRefreshing];
    });
    
}

- (void)Clicked:(UIBarButtonItem *)button
{
    Detail_fanggeViewController *fang = [[Detail_fanggeViewController alloc] init];
    [self.navigationController pushViewController:fang animated:YES];
    [fang release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
